<template>
  <div class="member-analysis">
    <el-row :gutter="20" v-if="!loading">
      <el-col :span="24">
        <el-card class="overview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>会员概览</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-box">
                <div class="stat-value">{{ memberData.totalMembers }}</div>
                <div class="stat-label">会员总数</div>
                <div class="stat-trend up" v-if="memberData.newMembersGrowth > 0">
                  <el-icon><ArrowUp /></el-icon> {{ memberData.newMembersGrowth }}%
                </div>
                <div class="stat-trend down" v-else-if="memberData.newMembersGrowth < 0">
                  <el-icon><ArrowDown /></el-icon> {{ Math.abs(memberData.newMembersGrowth) }}%
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-box primary">
                <div class="stat-value">{{ memberData.newMembers }}</div>
                <div class="stat-label">新增会员</div>
                <div class="stat-period">本周期内</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-box success">
                <div class="stat-value">{{ memberData.activeMembers }}</div>
                <div class="stat-label">活跃会员</div>
                <div class="stat-period">本周期内</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-box warning">
                <div class="stat-value">{{ memberData.retentionRate }}%</div>
                <div class="stat-label">留存率</div>
                <div class="stat-period">近30天</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>会员增长趋势</h3>
            </div>
          </template>
          <div class="chart-container">
            <div ref="memberGrowthChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="12" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>会员等级分布</h3>
            </div>
          </template>
          <div class="chart-container half-height">
            <div ref="memberLevelChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="12" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>会员性别分布</h3>
            </div>
          </template>
          <div class="chart-container half-height">
            <div ref="memberGenderChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>会员消费统计</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box info">
                <div class="stat-value">¥{{ formatMoney(memberData.avgConsumption) }}</div>
                <div class="stat-label">平均消费金额</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box info">
                <div class="stat-value">{{ memberData.avgFrequency }}</div>
                <div class="stat-label">平均消费频次</div>
                <div class="stat-period">次/月</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box success">
                <div class="stat-value">¥{{ formatMoney(memberData.maxConsumption) }}</div>
                <div class="stat-label">最高消费金额</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box primary">
                <div class="stat-value">¥{{ formatMoney(memberData.totalConsumption) }}</div>
                <div class="stat-label">会员总消费</div>
                <div class="stat-period">本周期内</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>会员年龄分布</h3>
            </div>
          </template>
          <div class="chart-container">
            <div ref="memberAgeChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>高价值会员</h3>
              <el-button type="primary" size="small">导出名单</el-button>
            </div>
          </template>
          <el-table :data="memberData.topMembers" stripe style="width: 100%">
            <el-table-column prop="memberId" label="会员ID" width="100" />
            <el-table-column prop="name" label="会员姓名" width="120" />
            <el-table-column prop="level" label="会员等级" width="100">
              <template #default="scope">
                <el-tag 
                  :type="getMemberLevelTag(scope.row.level)"
                  effect="dark"
                >
                  {{ scope.row.level }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="registerDate" label="注册日期" width="120" />
            <el-table-column prop="lastVisit" label="最近消费" width="120" />
            <el-table-column prop="totalSpent" label="累计消费" width="150">
              <template #default="scope">
                ¥{{ formatMoney(scope.row.totalSpent) }}
              </template>
            </el-table-column>
            <el-table-column prop="orderCount" label="消费次数" width="100" />
            <el-table-column prop="avgOrderValue" label="平均订单" width="150">
              <template #default="scope">
                ¥{{ formatMoney(scope.row.avgOrderValue) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="primary" size="small" link>详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%">
        <template #template>
          <el-skeleton-item variant="h3" style="width: 30%" />
          <el-skeleton-item variant="text" style="margin-top: 20px; width: 100%" />
          <el-skeleton-item variant="text" style="width: 100%" />
          <el-skeleton-item variant="text" style="width: 100%" />
        </template>
      </el-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'

// 属性
const props = defineProps({
  dateRange: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['refresh'])

// 图表引用
const memberGrowthChart = ref(null)
const memberLevelChart = ref(null)
const memberGenderChart = ref(null)
const memberAgeChart = ref(null)

// 模拟数据 - 实际项目中应该从 props.reportData 获取
const memberData = reactive({
  totalMembers: 2347,
  newMembers: 156,
  activeMembers: 876,
  retentionRate: 68.5,
  newMembersGrowth: 12.4,
  
  avgConsumption: 235.68,
  avgFrequency: 2.3,
  maxConsumption: 1687.50,
  totalConsumption: 206843.25,
  
  // 会员增长趋势数据
  growthTrend: [
    { date: '2023-04-01', total: 1985, new: 28, active: 645 },
    { date: '2023-04-08', total: 2024, new: 39, active: 678 },
    { date: '2023-04-15', total: 2087, new: 63, active: 712 },
    { date: '2023-04-22', total: 2142, new: 55, active: 734 },
    { date: '2023-04-29', total: 2191, new: 49, active: 752 },
    { date: '2023-05-06', total: 2234, new: 43, active: 785 },
    { date: '2023-05-13', total: 2285, new: 51, active: 812 },
    { date: '2023-05-20', total: 2347, new: 62, active: 876 }
  ],
  
  // 会员等级分布
  levelDistribution: [
    { level: '普通会员', count: 1425, value: 1425 },
    { level: '银卡会员', count: 586, value: 586 },
    { level: '金卡会员', count: 245, value: 245 },
    { level: '钻石会员', count: 91, value: 91 }
  ],
  
  // 会员性别分布
  genderDistribution: [
    { gender: '男', count: 1152, value: 1152 },
    { gender: '女', count: 1047, value: 1047 },
    { gender: '未知', count: 148, value: 148 }
  ],
  
  // 会员年龄分布
  ageDistribution: [
    { age: '18-24岁', count: 328 },
    { age: '25-30岁', count: 685 },
    { age: '31-40岁', count: 842 },
    { age: '41-50岁', count: 345 },
    { age: '51-60岁', count: 112 },
    { age: '60岁以上', count: 35 }
  ],
  
  // 高价值会员列表
  topMembers: [
    { memberId: 'M100235', name: '张三', level: '钻石会员', registerDate: '2021-05-15', lastVisit: '2023-05-18', totalSpent: 25678.50, orderCount: 45, avgOrderValue: 570.63 },
    { memberId: 'M100126', name: '李四', level: '金卡会员', registerDate: '2021-08-22', lastVisit: '2023-05-17', totalSpent: 18965.25, orderCount: 38, avgOrderValue: 499.09 },
    { memberId: 'M100578', name: '王五', level: '钻石会员', registerDate: '2022-01-05', lastVisit: '2023-05-19', totalSpent: 16782.30, orderCount: 29, avgOrderValue: 578.70 },
    { memberId: 'M100892', name: '赵六', level: '金卡会员', registerDate: '2022-03-18', lastVisit: '2023-05-15', totalSpent: 12567.80, orderCount: 25, avgOrderValue: 502.71 },
    { memberId: 'M101023', name: '钱七', level: '银卡会员', registerDate: '2022-06-30', lastVisit: '2023-05-16', totalSpent: 9876.40, orderCount: 22, avgOrderValue: 448.93 }
  ]
})

// 格式化金额
function formatMoney(value) {
  return value.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
}

// 获取会员等级对应的标签类型
function getMemberLevelTag(level) {
  const levelMap = {
    '普通会员': 'info',
    '银卡会员': '',
    '金卡会员': 'warning',
    '钻石会员': 'success'
  }
  
  return levelMap[level] || 'info'
}

// 初始化会员增长趋势图表
function initMemberGrowthChart() {
  if (!memberGrowthChart.value) return
  
  const chart = echarts.init(memberGrowthChart.value)
  
  const dates = memberData.growthTrend.map(item => {
    const date = new Date(item.date)
    return `${date.getMonth() + 1}/${date.getDate()}`
  })
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['会员总数', '新增会员', '活跃会员'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: [
      {
        type: 'value',
        name: '会员总数',
        position: 'left'
      },
      {
        type: 'value',
        name: '新增/活跃',
        position: 'right'
      }
    ],
    series: [
      {
        name: '会员总数',
        type: 'line',
        data: memberData.growthTrend.map(item => item.total),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '新增会员',
        type: 'bar',
        yAxisIndex: 1,
        data: memberData.growthTrend.map(item => item.new),
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '活跃会员',
        type: 'line',
        yAxisIndex: 1,
        data: memberData.growthTrend.map(item => item.active),
        smooth: true,
        lineStyle: {
          width: 2,
          color: '#E6A23C'
        },
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化会员等级分布图表
function initMemberLevelChart() {
  if (!memberLevelChart.value) return
  
  const chart = echarts.init(memberLevelChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: memberData.levelDistribution.map(item => item.level)
    },
    series: [
      {
        name: '会员等级',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { 
            value: memberData.levelDistribution[0].value, 
            name: memberData.levelDistribution[0].level,
            itemStyle: { color: '#909399' }
          },
          { 
            value: memberData.levelDistribution[1].value, 
            name: memberData.levelDistribution[1].level,
            itemStyle: { color: '#C0C4CC' }
          },
          { 
            value: memberData.levelDistribution[2].value, 
            name: memberData.levelDistribution[2].level,
            itemStyle: { color: '#E6A23C' }
          },
          { 
            value: memberData.levelDistribution[3].value, 
            name: memberData.levelDistribution[3].level,
            itemStyle: { color: '#67C23A' }
          }
        ]
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化会员性别分布图表
function initMemberGenderChart() {
  if (!memberGenderChart.value) return
  
  const chart = echarts.init(memberGenderChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: memberData.genderDistribution.map(item => item.gender)
    },
    series: [
      {
        name: '性别分布',
        type: 'pie',
        radius: '55%',
        center: ['50%', '45%'],
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        data: [
          { 
            value: memberData.genderDistribution[0].value, 
            name: memberData.genderDistribution[0].gender,
            itemStyle: { color: '#409EFF' }
          },
          { 
            value: memberData.genderDistribution[1].value, 
            name: memberData.genderDistribution[1].gender,
            itemStyle: { color: '#F56C6C' }
          },
          { 
            value: memberData.genderDistribution[2].value, 
            name: memberData.genderDistribution[2].gender,
            itemStyle: { color: '#909399' }
          }
        ]
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化会员年龄分布图表
function initMemberAgeChart() {
  if (!memberAgeChart.value) return
  
  const chart = echarts.init(memberAgeChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: memberData.ageDistribution.map(item => item.age)
    },
    yAxis: {
      type: 'value',
      name: '会员数量'
    },
    series: [
      {
        name: '会员数量',
        type: 'bar',
        barWidth: '60%',
        data: memberData.ageDistribution.map(item => item.count),
        itemStyle: {
          color: function(params) {
            const colorList = ['#91cc75', '#5470c6', '#ee6666', '#73c0de', '#3ba272', '#fc8452']
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 监听日期范围变化
watch(() => props.dateRange, () => {
  if (props.dateRange && props.dateRange.length === 2) {
    emit('refresh')
  }
}, { deep: true })

// 组件挂载后初始化图表
onMounted(() => {
  // 模拟延迟加载
  setTimeout(() => {
    initMemberGrowthChart()
    initMemberLevelChart()
    initMemberGenderChart()
    initMemberAgeChart()
  }, 500)
})
</script>

<style scoped>
.member-analysis {
  width: 100%;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.subtitle {
  font-size: 14px;
  color: #909399;
}

.overview-card {
  margin-bottom: 20px;
}

.stat-box {
  padding: 20px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
  position: relative;
}

.stat-value {
  font-size: 26px;
  font-weight: bold;
  color: #409EFF;
}

.stat-box.primary .stat-value {
  color: #409EFF;
}

.stat-box.success .stat-value {
  color: #67C23A;
}

.stat-box.warning .stat-value {
  color: #E6A23C;
}

.stat-box.danger .stat-value {
  color: #F56C6C;
}

.stat-box.info .stat-value {
  color: #909399;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 8px;
}

.stat-period {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.stat-trend {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.stat-trend.up {
  color: #67C23A;
}

.stat-trend.down {
  color: #F56C6C;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.chart-container.half-height {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 